package com.example.demo.excel;

import cn.hutool.core.date.DateUtil;
import cn.hutool.poi.excel.ExcelUtil;
import cn.hutool.poi.excel.ExcelWriter;
import org.junit.Test;

import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @author pengyifeng
 * @version 2.0
 * @ClassName excelDemo.java
 * @Description 基础excel导出
 * @createTime 2021年11月15日 10:49:00
 */
//@RestController
public class ExcelDemo {
    //@RequestMapping("/export")
    //void export(HttpServletResponse response) throws FileNotFoundException {
    @Test
    public void export() throws FileNotFoundException {
        List list = new ArrayList<>();
        list.add(new ExcelUser("zhangsan", "1231", new Date()));
        list.add(new ExcelUser("zhangsan1", "1232", new Date()));
        list.add(new ExcelUser("zhangsan2", "1233", new Date()));
        list.add(new ExcelUser("zhangsan3", "1234", new Date()));
        list.add(new ExcelUser("zhangsan4", "1235", new Date()));
        list.add(new ExcelUser("zhangsan5", "1236", DateUtil.date(new Date())));
        // 通过工具类创建writer，默认创建xls格式
        ExcelWriter writer = ExcelUtil.getWriter();
        // 自定义标题别名
        writer.addHeaderAlias("name", "姓名");
        writer.addHeaderAlias("age", "年龄");
        writer.addHeaderAlias("birthDay", "生日");
        // 合并单元格后的标题行，使用默认标题样式
        writer.merge(2, "申请人员信息");
        // 一次性写出内容，使用默认样式，强制输出标题
        writer.write(list, true);
        // out为OutputStream，需要写出到的目标流
        // response为HttpServletResponse对象
        //response.setContentType("application/vnd.ms-excel;charset=utf-8");
        // test.xls是弹出下载对话框的文件名，不能为中文，中文请自行编码
        //String name = StringUtils.toUtf8String("申请学院");
        try {
            String name = new String("申请学院".getBytes("utf-8") , "utf-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        //浏览器请求下载解除注释
        //response.setHeader("Content-Disposition", "attachment;filename=" + name + ".xls");
        //ServletOutputStream out = null;
        //try {
        //    out = response.getOutputStream();
        //    writer.flush(out, true);
        //} catch (IOException e) {
        //    e.printStackTrace();
        //} finally {// 关闭writer，释放内存  writer.close(); }
        //    // 此处记得关闭输出Servlet流
        //    IoUtil.close(out);
        //}

        //本地下载
        FileOutputStream outputStream = new FileOutputStream("D:/home/excel/excelDemo.xlsx");
        writer.flush(outputStream, true);
        writer.close();
    }
}
